package com.cheng.lesson02;

import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
import java.io.OutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

//客户端上传文件
public class TestClientDemon02 {
    public static void main(String[] args) throws IOException {
        //1.创建socket连接
        Socket socket = new Socket(InetAddress.getByName("127.0.0.1"),8888);
        //2.创建输出流
        OutputStream os = socket.getOutputStream();
        //3.读取文件
        FileInputStream fis = new FileInputStream(new File("1.png"));
        //4.写出文件
        byte[] buffer1 = new byte[1024];
        int len;
        while((len=fis.read(buffer1))!=-1){
            os.write(buffer1,0,len);
        }
        //告知服务器，客户端已经上传文件完毕
        socket.shutdownOutput();

        //确认服务端成功接收文件，再断开和服务器的连接
        InputStream inputStream = socket.getInputStream();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buffer2 = new byte[1024];
        int len1;
        while((len1=inputStream.read(buffer2))!=-1){
            baos.write(buffer2,0,len1);
        }
        System.out.println(baos.toString());//转换成string类型


        fis.close();
        os.close();
        socket.close();
    }
}
